package charlie.shop.warehouse;

import com.charlie.beans.Product;
import com.charlie.sessions.ProductFacadeLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Remove selected product from catalog
 * @author Gleb
 */
@WebServlet(name = "DeleteProduct", urlPatterns = {"/warehouse/DeleteProduct"})
public class DeleteProduct extends HttpServlet {

    @EJB
    private ProductFacadeLocal productFacade;

    /**
     * Displays delete product page.
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/warehouse/ListOfProducts.jsp").forward(request, response);
    }

    /**
     * Displays delete product page.
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Get an id parameter and delete product.
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("id") != null) {
            Product product = productFacade.find(Integer.valueOf(request.getParameter("id")));
            product.setStatus(0);
            productFacade.edit(product);
            response.sendRedirect(request.getContextPath() + "/warehouse/products");
            return;
        }
        processRequest(request, response);
    }    
}
